<template>
  <div class="chat-container">
    <div class="chat-sidebar">
      <div class="chat-rooms">
        <h2>聊天列表</h2>
        <div class="room-list">
          <div
            v-for="room in chatStore.rooms"
            :key="room.id"
            class="room-item"
            :class="{ active: chatStore.currentRoom?.id === room.id }"
            @click="selectRoom(room)"
          >
            <div class="room-info">
              <h3>{{ room.name }}</h3>
              <p v-if="room.lastMessage" class="last-message">
                {{ room.lastMessage.content }}
              </p>
            </div>
            <div class="room-meta">
              <span v-if="room.lastMessage" class="timestamp">
                {{ formatTime(room.lastMessage.timestamp) }}
              </span>
              <span v-if="room.unreadCount" class="unread-count">
                {{ room.unreadCount }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="chat-main">
      <template v-if="chatStore.currentRoom">
        <div class="chat-header">
          <h2>{{ chatStore.currentRoom.name }}</h2>
        </div>

        <div class="message-list" ref="messageList">
          <div v-for="message in chatStore.messages" :key="message.id" class="message-item">
            <div class="message-content" :class="{ 'own-message': isOwnMessage(message) }">
              <div class="message-header">
                <span class="sender">{{ message.senderName }}</span>
                <span class="time">{{ formatTime(message.timestamp) }}</span>
              </div>
              <div class="message-body">
                <template v-if="message.type === 'text'">
                  {{ message.content }}
                </template>
                <template v-else-if="message.type === 'image'">
                  <img :src="message.fileUrl" alt="图片消息" @click="previewImage(message.fileUrl)">
                </template>
                <template v-else-if="message.type === 'file'">
                  <a :href="message.fileUrl" target="_blank" download>
                    <i class="fas fa-file"></i> {{ message.content }}
                  </a>
                </template>
              </div>
            </div>
          </div>
        </div>

        <div class="message-input">
          <div class="input-toolbar">
            <button @click="triggerFileInput('image')" title="发送图片">
              <i class="fas fa-image"></i>
            </button>
            <button @click="triggerFileInput('file')" title="发送文件">
              <i class="fas fa-paperclip"></i>
            </button>
          </div>
          <div class="input-area">
            <textarea
              v-model="messageInput"
              @keydown.enter.prevent="sendMessage"
              placeholder="输入消息..."
              rows="3"
            ></textarea>
            <button @click="sendMessage" :disabled="!messageInput.trim()">
              发送
            </button>
          </div>
        </div>

        <input
          type="file"
          ref="imageInput"
          accept="image/*"
          style="display: none"
          @change="handleFileUpload('image')"
        >
        <input
          type="file"
          ref="fileInput"
          style="display: none"
          @change="handleFileUpload('file')"
        >
      </template>

      <div v-else class="no-chat-selected">
        <p>选择一个聊天开始交谈</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useChatStore } from '../stores/chat.store'
import { useAuthStore } from '../stores/auth.store'

const chatStore = useChatStore()
const authStore = useAuthStore()

const messageInput = ref('')
const messageList = ref<HTMLElement | null>(null)
const imageInput = ref<HTMLInputElement | null>(null)
const fileInput = ref<HTMLInputElement | null>(null)

const isOwnMessage = (message: any) => {
  return message.senderId === authStore.user?.id
}

const formatTime = (timestamp: string) => {
  const date = new Date(timestamp)
  const now = new Date()
  
  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }
  return date.toLocaleDateString('zh-CN')
}

const selectRoom = async (room: any) => {
  try {
    await chatStore.joinRoom(room.id)
    scrollToBottom()
  } catch (error) {
    console.error('Failed to join room:', error)
  }
}

const sendMessage = async () => {
  if (!messageInput.value.trim()) return
  
  try {
    await chatStore.sendMessage(messageInput.value)
    messageInput.value = ''
    await nextTick()
    scrollToBottom()
  } catch (error) {
    console.error('Failed to send message:', error)
  }
}

const triggerFileInput = (type: 'image' | 'file') => {
  const input = type === 'image' ? imageInput.value : fileInput.value
  input?.click()
}

const handleFileUpload = async (type: 'image' | 'file', event: Event) => {
  const input = event.target as HTMLInputElement
  if (!input.files?.length) return

  const file = input.files[0]
  try {
    const formData = new FormData()
    formData.append('file', file)

    const response = await fetch('/api/chat/upload', {
      method: 'POST',
      body: formData
    })

    const { fileUrl } = await response.json()
    await chatStore.sendMessage(file.name, type, fileUrl)
    input.value = ''
  } catch (error) {
    console.error('Failed to upload file:', error)
  }
}

const scrollToBottom = () => {
  if (messageList.value) {
    messageList.value.scrollTop = messageList.value.scrollHeight
  }
}

const previewImage = (url: string) => {
  window.open(url, '_blank')
}

onMounted(async () => {
  chatStore.initializeSocket()
  await chatStore.loadRooms()
})

onUnmounted(() => {
  chatStore.disconnect()
})
</script>

<style scoped>
.chat-container {
  display: flex;
  height: 100%;
  background-color: #f5f5f5;
}

.chat-sidebar {
  width: 300px;
  background: white;
  border-right: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;
}

.chat-rooms {
  flex: 1;
  overflow-y: auto;
}

.chat-rooms h2 {
  padding: 1rem;
  margin: 0;
  border-bottom: 1px solid #e8e8e8;
}

.room-list {
  padding: 1rem 0;
}

.room-item {
  display: flex;
  justify-content: space-between;
  padding: 1rem;
  cursor: pointer;
  transition: background-color 0.2s;
}

.room-item:hover {
  background-color: #f5f5f5;
}

.room-item.active {
  background-color: #e8f5e9;
}

.room-info {
  flex: 1;
  margin-right: 1rem;
}

.room-info h3 {
  margin: 0;
  font-size: 1rem;
  margin-bottom: 0.25rem;
}

.last-message {
  color: #666;
  font-size: 0.875rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.room-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.timestamp {
  font-size: 0.75rem;
  color: #999;
}

.unread-count {
  background: #4CAF50;
  color: white;
  padding: 0.25rem 0.5rem;
  border-radius: 1rem;
  font-size: 0.75rem;
  margin-top: 0.25rem;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
}

.chat-header {
  padding: 1rem;
  border-bottom: 1px solid #e8e8e8;
}

.chat-header h2 {
  margin: 0;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
}

.message-item {
  margin-bottom: 1rem;
}

.message-content {
  max-width: 70%;
  padding: 0.75rem;
  border-radius: 8px;
  background: #f5f5f5;
}

.message-content.own-message {
  margin-left: auto;
  background: #e8f5e9;
}

.message-header {
  margin-bottom: 0.5rem;
  font-size: 0.875rem;
}

.sender {
  font-weight: bold;
  margin-right: 0.5rem;
}

.time {
  color: #999;
}

.message-body img {
  max-width: 100%;
  border-radius: 4px;
  cursor: pointer;
}

.message-body a {
  color: #4CAF50;
  text-decoration: none;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.message-input {
  padding: 1rem;
  border-top: 1px solid #e8e8e8;
}

.input-toolbar {
  margin-bottom: 0.5rem;
}

.input-toolbar button {
  background: none;
  border: none;
  padding: 0.5rem;
  cursor: pointer;
  color: #666;
  font-size: 1.2rem;
}

.input-toolbar button:hover {
  color: #4CAF50;
}

.input-area {
  display: flex;
  gap: 1rem;
}

.input-area textarea {
  flex: 1;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: none;
  font-family: inherit;
}

.input-area button {
  padding: 0.75rem 1.5rem;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.input-area button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.no-chat-selected {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
}
</style>